import { validatePhone, validateEmail, validatePassword, validatePasswordStrength } from '@/utils/validation'
import { objHasOwn } from '@/utils/object'

export const createForm = (form = {}) => {
  return {
    username: form.username || '',
    password: form.password || '',
    email: form.email || '',
    checkPass: form.checkPass || ''
  }
}

const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!validatePhone(value)) {
    callback(new Error('请输入正确的手机号'))
    // callback(new Error('账号长度不小于6位'))
  } else {
    callback()
  }
}

const validateMail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入邮箱'))
  } else if (!validateEmail(value)) {
    callback(new Error('请输入正确的邮箱'))
  } else {
    callback()
  }
}

const validatePass = (rule, value, callback, vm) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!validatePassword(value)) {
    callback(new Error('密码长度在8到12位之间'))
  } else if (validatePasswordStrength(value) < 5) {
    callback(new Error('密码必须包含大写、小写、数字、特殊字符'))
  } else {
    if (objHasOwn(vm.formData, 'checkPass') && vm.formData.checkPass !== '') {
      vm.$refs.formRef.validateField('checkPass')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback, vm) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== vm.formData.password) {
    callback(new Error('两次输入密码不一致!'))
  } else if (!validatePassword(value)) {
    callback(new Error('密码长度不小于6位'))
  } else {
    callback()
  }
}

export const createFormFules = vm => {
  return {
    username: { validator: validateUsername, trigger: 'blur' },
    email: { validator: validateMail, trigger: 'blur' },
    password: [{ validator: (rule, value, callback) => validatePass(rule, value, callback, vm), trigger: 'blur' }],
    checkPass: [{ validator: (rule, value, callback) => validatePass2(rule, value, callback, vm), trigger: 'blur' }]
  }
}
